package com.limao.Tool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.TimerTask;

import com.Aliyun.alipay.config.AlipayConfig;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.limao.CacheManager.CrowdOrderCache;
import com.limao.DbConnection.DbConnectionManager;
import com.limao.dataEnum.OnlinePayEnum;

public class TaskOneForAlipay  extends TimerTask{

	
	public TaskOneForAlipay(){

	}
	
	@Override
	public void run() {
		
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs =null;
		ArrayList<String> order_snList = new ArrayList<String>();
		try {
			
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement("select order_sn from cd_sys_order where createtime>? and state=1 and paytype=0 ");
			long nowt=CacheClass.getTime();
			long t24=24*3600*1000;
			pstmt.setLong(1, nowt-t24);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				order_snList.add(rs.getString("order_sn"));
			}
		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		int paytype=OnlinePayEnum.appliy.getIntVlue();
		for(String order_sn:order_snList)
		{
			
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",AlipayConfig.getAliAPPID(),AlipayConfig.getAliPrivateKey(),"json",AlipayConfig.input_charset,AlipayConfig.ali_public_key);
			AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
			request.setBizContent("{\"out_trade_no\":\""+order_sn+"\"}");
			try {
				AlipayTradeQueryResponse response = alipayClient.execute(request);
				order_sn=response.getOutTradeNo();
				String trade_status=response.getTradeStatus();
				if(trade_status.equals("TRADE_SUCCESS")){
					 try {
						CrowdOrderCache.getInstance().Deal_Order(order_sn,paytype,false, "");
						Thread.sleep(100);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				
				
			} catch (AlipayApiException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		this.cancel();
		
	}
	
}